package ar.edu.itba.cg.model;

import com.jme.bounding.BoundingSphere;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.util.Timer;
import com.jmex.physics.DynamicPhysicsNode;
import com.jmex.physics.material.Material;

public class Ball {

	private final static int EPSILON=150;
	private static final float EPSILON_STOP = 1f;
	private DynamicPhysicsNode node;
	private Vector3f origin;
	private Vector3f lastPos;
	private long lastTime;
	
	public Ball(DynamicPhysicsNode node, Vector3f origin){
		this.node= node;
		this.origin= new Vector3f(origin);
		setup();
		
		node.getLocalTranslation().set(origin);
	}
	
	public void resetPos(){
		node.setLinearVelocity(new Vector3f(0,0,0));
		node.setAngularVelocity(new Vector3f(0,0,0));
		node.getLocalTranslation().set(origin);
		node.setAffectedByGravity(true);
		lastPos= new Vector3f(origin);
		lastTime=0;
	}
	
	public boolean isOutTheCourt(){
		return (origin.getY() - node.getLocalTranslation().getY() > EPSILON);
	}
	
	public void setup(){
		/* Load the ball model */
		Node model= FactoryModel.loadBall();
		
		/* Setup the ball physics */
		model.setModelBound(new BoundingSphere());
		model.updateModelBound();
		model.setLocalScale(0.9f);
		node.attachChild(model);
		node.generatePhysicsGeometry();
		node.rest();
    	node.setMaterial(Material.GRANITE);
    	node.computeMass();
    	node.setAffectedByGravity(true);
    	//node.rest();
    	//node.setMass(7.5f);

	}
	
	public void shootMe(float x, float y, float z){
	   	node.setAffectedByGravity(true);
	   	Vector3f s = new Vector3f(x, y, -z);
	   	node.addForce(s);
	}

	public boolean isStoped(Timer timer) {
		boolean ans=false;
		
		if(lastPos!=null){
			if(lastTime!=0){				
				if(timer.getTime()-lastTime>1000){					
					ans=Math.abs(lastPos.getZ()-node.getLocalTranslation().getZ())<EPSILON_STOP;
					lastPos= new Vector3f(node.getLocalTranslation());
					lastTime= timer.getTime();
				}
			}else{
				lastTime= timer.getTime();
			}
		}
		return ans;
	}

	public Spatial getNode() {
		return node;
	}
	
}

